import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { UserService } from 'src/app/service/user.service';
import { YearawardService } from '../../yearaward.service';
import { BaseService } from 'src/app/service/base.service';
import { UtilsService } from 'src/app/service/utils.service';
import type { Subscription } from 'rxjs';

@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  styleUrls: ['./task.component.scss'],
})
export class TaskComponent implements OnInit, OnDestroy {
  @Input() timeConfig: any[] = [];
  // @Input() taskDialogSub: Subject<EndYear.Renqi.ITaskItem>;
  /* ___ _ ___ */
  public deployUrl: string; /* 资源地址前缀 */
  private reshing: Subscription = null; /* 订阅刷新 */
  private observer: IntersectionObserver; /* 实例 Inersction Observer */
  /* ___ _ ___ */
  public isPC = false; /* 是否pc */
  public isAndroid = false; /* 是否安卓 */
  public onRefrash = false; /* 刷新中 */
  public isAllLiveFinshed = false; /* 直播任务全部结束 */
  public pageSize = 30;
  public taskDetailMap = new Map<
    number,
    { total: number; isCumulative: boolean }
  >();

  /* ___ _ ___ */

  public finished: any[] = [];
  public unFinished: any[] = [];

  public remainNumber;
  public verified;

  constructor(
    private userService: UserService,
    private yearawardService: YearawardService,
    public baseService: BaseService,
    private utilsService: UtilsService
  ) {}

  ngOnInit(): void {
    // 获取
    this.deployUrl = this.userService.getDeployUrl();
    this.isPC = this.userService.getIsPc();
    this.isAndroid = this.utilsService.getBrowserVersion();

    this.init();
    // 组件刷新通信
    // 组件刷新通信
    this.reshing = this.utilsService.MsgSub.subscribe(() => {
      this.init();
    });
  }
  ngOnDestroy(): void {
    if (this.reshing) {
      this.reshing.unsubscribe();
    }
  }

  init() {
    // 请求数据
    this.getList();
    // 任务写死一些数据
    /* 累计观看直播1/5/15/30分钟,分别获得人气票*5张 */
    this.taskDetailMap.set(2, {
      total: 50,
      isCumulative: false,
    });
    /* 每天访问活动页面，贵族用户获得10张，普通用户获得5张 */
    this.taskDetailMap.set(4, { total: 10, isCumulative: false });
    /* 累计观看直播1/5/15/30分钟,分别获得人气票*5张 */
    this.taskDetailMap.set(36, { total: 20, isCumulative: true });
    /* 累计观看直播60/120分钟,分别获得人气票*10个 */
    this.taskDetailMap.set(38, { total: 20, isCumulative: true });
    /* 累计观看直播180分钟,获得人气票*20张 */
    this.taskDetailMap.set(39, { total: 20, isCumulative: true });
  }

  /**
   * @description: 初始化请求列表
   */
  getList() {
    this.yearawardService.getUserWatchTime(
      (res) => {
        this.remainNumber = res.data.num;
        console.log('getUserWatchTime=>', this.remainNumber);
        this.yearawardService.getDailyTask(
          ({ code, data }) => {
            if (code === 200) {
              const { finalResult, remainNumber } = data as EndYear.Renqi.ITask;
              console.log('=>', finalResult, remainNumber);

              const {
                user: { cumulativeInRoomTimeGather, angel },
              } = finalResult; /* {cumulativeInRoomTimeGather:[] ,angel:[]} */

              /* 直播任务全部结束 */
              const isAllLiveFinshed = cumulativeInRoomTimeGather.every(
                (_) => _.allComplete
              );

              this.isAllLiveFinshed = isAllLiveFinshed;

              const [finished, unFinished] = [
                ...cumulativeInRoomTimeGather,
                ...angel,
              ]
                .sort((i, j) => i.sort - j.sort) /* 排序 */
                .reduce(
                  (pre, cur) => {
                    const { allComplete } = cur;
                    return allComplete
                      ? [[...pre[0], cur], pre[1]]
                      : [pre[0], [...pre[1], cur]];
                  },
                  [[], []]
                );

              console.log('yes=>', finished, unFinished);
              this.finished = finished;
              this.unFinished = unFinished;

              this.remainNumber = Math.ceil(
                remainNumber / 60
              ); /* 接口为s 转换为分钟 */
            }
          },
          this.baseService.getUserid(),
          () => {}
        );
      },
      () => {},
      this.baseService.getUserid()
    );
  }

  /**
   * @param task
   * @description: 选择任务
   */
  onTaskChoose(task) {
    if (task.code === 4) {
      /* 登录任务 不跳转 */
      this.baseService.showToast('已完成该任务', 1500);
      return;
    }
    this.yearawardService.getAnchorroom(
      (res) => {
        if (res.code === 200) {
          const obj = { ...res.data };
          obj.uid = res.data.anchorUid;
          obj.livimage =
            res.data.avatarUrl ||
            'https://image.91banban.com/moren_touxiang.png';
          obj.livImage =
            res.data.avatarUrl ||
            'https://image.91banban.com/moren_touxiang.png';

          this.utilsService.gotoRoom({ ...obj }, 'anchor', []);
        } else {
          this.baseService.showToast(res.message, 1500);
        }
      },
      () => {}
    );
  }
}
